package com.wzy.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class TokenVerifyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");

        if (!StringUtils.isNotEmpty(token)){

            /*
            通过context.setSendZuulResponse(false)可以终止请求的转发,但是只在pre类型的过滤器中设置才可以,
            原因是route 类型的filter 第一位就是RibbonRoutingFilter，这个filter就是用于向目标服务发起请求的
            ，而在这个RibbonRoutingFilter的shouldFilter()里面，判断了只有currentContext的sendZuulResponse中为true才会
            执行RibbonRoutingFilter的run()方法去发起目标服务调用。
             */

            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            currentContext.setResponseBody("unAuthrized");
        }
        return "TokenVerifyFilter";
    }
}
